<template>
  <div>
	  <div class="ifttt-cont">
		  <!--触发条件-->
		  <div class="position-relative">
			  <div slot="title" class="flex-com mar-btm">
				  <div class="label-title font-weight-bold">触发条件</div>
				  <el-input v-model="ruleForm.name" class="width-input" size="mini" placeholder="触发条件"></el-input>
			  </div>
			  <IftttFiled :rule-form="ruleForm"></IftttFiled>
			  <div
				  style="position: absolute; bottom: 0; right: 0"
				  class="font-color-primary font-size-12 font-weight-bold cursor-pointer"
				  @click="addEvents">
				  <i class="iconfont icon-tianjia"></i><span class="mar-lft-5">添加规则</span>
			  </div>
		  </div>
		  <div class="divider mar-btm"></div>
		  <!--真值反馈事件-->
		  <div v-if="ruleForm.actions.length">
			  <el-tabs v-model="activeRuleIdx" type="border-card">
				  <el-tab-pane
					  v-for="(action, idx) in ruleForm.actions" :key="idx" :name="`${idx}`">
					  <template slot="label">
						  <i class="header-icon el-icon-info font-size-14 ">规则{{idx + 1}}</i>
					  </template>
					  <IftttState :ruleForm="action" :conditions="ruleForm" :ifttt="true" ref="iftttState">
						  <template slot="copyRule">
							  <span class="el-icon-copy-document cursor-pointer font-hover-primary" @click="copyEvent(idx)"></span>
							  <span class="el-icon-delete cursor-pointer font-hover-danger mar-lft-10" @click="deleteEvent(idx)"></span>
						  </template>
					  </IftttState>
				  </el-tab-pane>
			  </el-tabs>
			  <div class="text-align-right mar-top">
				  <el-button @click="cancel" size="small">取 消</el-button>
				  <el-button type="primary" @click="confirm" size="small">确 定</el-button>
			  </div>
		  </div>
		  <EmptyContent v-else :min-height="300" :image-size="150" empty-text="暂无规则配置"></EmptyContent>
	  </div>
  </div>
</template>
<script>
	import {confirmHandle, deepCopy} from "@/utils";
	import IftttFiled from "@/page/IDE/editor/dock/component/IftttFiled.vue";
	import IftttState from "@/page/IDE/editor/dock/component/IftttState.vue";

  export default {
    name: "IftttLogicForm",
    components: {
      IftttFiled, IftttState
    },
    props: {
			ruleForm: {
				type: Object,
				default: () => {
					return {
						type: "",
						key: "",
						actions: [],
						name: '触发条件',
						npKeyIndex: 0,
						params: ''
					}
				}
			}
    },
    data() {
      return {
	      activeRuleIdx: '0',
      };
    },
    methods: {
      //添加真值反馈事件
      addEvents() {
        if (!this.verify()) return;
        this.ruleForm.actions.push({
          name: "自定义逻辑", //类似if else的作用 温度>18
          key: null,
          type: "iftttLogic",
          delay: 0,
          value: {
            conditions: [],
            actions: [],
            elseActions: [],
            enable: true,
            andOr: 'and'
          },
        });
	      this.activeRuleIdx = `${this.ruleForm.actions.length - 1}`;
      },
      // 删除规则
      deleteEvent(index) {
        confirmHandle({label: `确定要删除吗?`}).then(() => {
	        this.ruleForm.actions.splice(index, 1);
	        if (this.ruleForm.actions[index - 1]) {
		        this.activeRuleIdx = `${index - 1}`;
	        }
        }).catch(() => {
        });
      },
      // 复制规则
      copyEvent(index) {
        const action = this.ruleForm.actions[index];
        if (!action) return;
	      this.ruleForm.actions.splice(index, 0, deepCopy(action));
	      this.activeRuleIdx = `${this.ruleForm.actions.length - 1}`;
      },
	    //提交验证
	    verify() {
		    const lastValue = this.ruleForm.actions[this.ruleForm.actions.length - 1];
		    const conditions = lastValue ? lastValue.value.conditions : [];
		    const lastConditions = conditions[conditions.length - 1];
		    switch (this.ruleForm.type) {
			    case 'relatedSystem':
				    if (!this.ruleForm.value) {
					    this.$notify({title: '', message: '请填写完整房间属性触发条件', type: 'warning', duration: 3000});
					    return false;
				    }
				    break;
			    case 'relatedDeviceStatus':
				    if (!this.ruleForm.value || !this.ruleForm.params) {
					    this.$notify({title: '', message: '请填写完整设备状态触发条件', type: 'warning', duration: 3000});
					    return false;
				    }
				    break;
			    case 'relatedAtomic':
				    if (!this.ruleForm.value) {
					    this.$notify({title: '', message: '请填写完整组件变量触发条件', type: 'warning', duration: 3000});
					    return false;
				    }
				    break;
			    case 'relatedGlobal':
				    if (!this.ruleForm.value) {
					    this.$notify({title: '', message: '请填写完整全局变量触发条件', type: 'warning', duration: 3000});
					    return false;
				    }
				    break;
			    default:
				    return false;
		    }
		    // TODO 以下代码最后两个 else if 判断逻辑确认 Henry 2023-12-05 16:43:06
		    if (this.ruleForm.type === 'relatedDeviceStatus' && (!this.ruleForm.value || !this.ruleForm.params)) {
			    this.$notify({
				    message: '请填写完整设备触发条件',
				    type: 'warning',
				    duration: 3000,
			    });
			    return false;
		    } else if (this.ruleForm.type !== 'relatedDeviceStatus' && !this.ruleForm.value) {
			    this.$notify({
				    message: '请填写完整房间/组件触发条件',
				    type: 'warning',
				    duration: 3000,
			    });
			    return false;
		    } else if (lastValue !== undefined && lastConditions !== undefined && lastConditions.value2.value.length === 0 && lastConditions.value2.autoType !== 4) {
			    //判断条件属性必须 判断上一条内容为空 ，类型不是空值类型
			    this.$notify({
				    message: '请填写完整的判断条件！',
				    type: 'warning',
				    duration: 3000,
			    });
			    return false;
		    } else if (lastValue !== undefined && lastValue.value.actions.length === 0 && lastValue.value.elseActions.length === 0) {
			    //满足和不满足条件必须其中一个
			    this.$notify({
				    message: '请至少填写一项条件满足或不满足后触发的操作！',
				    type: 'warning',
				    duration: 3000,
			    });
			    return false;
		    } else {
			    return true;
		    }
	    },
	    cancel() {
				this.$emit('cancel');
	    },
	    confirm() {
		    if (!this.verify()) return;
		    this.$emit('confirm');
      },
    },
  };
</script>
<style lang="less" scoped>
  .ifttt-cont {
    width: 100%;

    .flex-com {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .label-title {
      min-width: 60px;
      color: @colorGray10;
      font-size: 14px;
      text-align: center;
      flex-shrink: 0;
    }

    .divider {
      height: 8px;
      background: @colorGray96;
      margin-left: -15px;
      margin-right: -15px;
    }

    .width-input {
      width: 350px;

      /deep/ .el-input__inner {
        width: 100%;
      }
    }
  }

  .header-icon {
    color: #e0572d;
  }
</style>
